package cn.xkai.exercise.a;

/**
 * @description: 反转字符串中的单词 III
 * 自己的思路：使用StringBuilder的setCharAt设置字符，根据提交结果可以发现setCharAt和charAt很占用时间
 * 借鉴的思路：转换成数组，根据数组下标使用异或交换字符
 * @author: kaixiang
 * @date: 2022-06-29
 **/
public class Solution20 {
    public String reverseWords(String s) {
        StringBuilder sb = new StringBuilder(s);
        int left = 0, right = 0;
        for (int i = 0; i < s.length(); i++) {
            if (i == s.length() - 1 || s.charAt(i) == ' ') {
                right = s.charAt(i) == ' ' ? i - 1 : i;
                while (left < right) {
                    sb.setCharAt(left, s.charAt(right));
                    sb.setCharAt(right, s.charAt(left));
                    left++;
                    right--;
                }
                sb.append(" ");
                left = i + 1;
            }
        }
        return sb.toString().trim();
    }

    public String reverseWordsRefer(String s) {
        char[] words = s.toCharArray();
        int left = 0, right = 0, len = s.length();
        for (int i = 0; i < len; i++) {
            if (i == len - 1 || words[i] == ' ') {
                right = words[i] == ' ' ? i - 1 : i;
                while (left < right) {
                    words[left] = (char) (words[left] ^ words[right]);
                    words[right] = (char) (words[left] ^ words[right]);
                    words[left] = (char) (words[left] ^ words[right]);
                    left++;
                    right--;
                }
                left = i + 1;
            }
        }
        return String.valueOf(words);
    }

    public static void main(String[] args) {
        String s = "Let's take LeetCode contest";
        Solution20 solution20 = new Solution20();
        System.out.println(solution20.reverseWords(s));
    }
}
